function reloadTable(params) {
    var postData;
    if (params) {
        postData = params;
    } else {
        postData = {};
    }
    postData['search.deleted_eq'] = false;
    $('#grid-table').jqGrid('setGridParam', {
        postData: postData, page: 1
    }).trigger('reloadGrid');
}

$(function(){

    function getSelectRowId() {
        var grid = $('#grid-table'), rowId;

        rowId = grid.getGridParam("selrow");
        if (!rowId) {
            $.app.alert("请选择一条记录");
            return null;
        }

        if (grid.getGridParam("selarrrow").length > 1) {
            $.app.alert("只能选择一条记录");
            return null;
        }

        return rowId;
    }

    function initValidationEngine() {
        //自定义ajax验证  ajax[ajaxNameCall] 放到验证规则的最后（放到中间只有当submit时才验证）
        $.validationEngineLanguage.allRules.ajaxNameCall= {
            url: ctx + '/showcase/sample/validate',
            //动态提取的数据。验证时一起发送
            extraDataDynamic : ['#id'],
            //验证失败时的消息
            //"alertText": "* 该名称已被其他人使用",
            //验证成功时的消息
            //"alertTextOk": "该名称可以使用",
            alertTextLoad: '* 正在验证，请稍等。。。'
        };
        $.validationEngineLanguage.allRules.username={
            "regex": /^\w{5,10}$/,
            "alertText": "* 5到10个字母、数字、下划线"
        };
        $("#editForm").validationEngine({promptPosition : 'bottomRight'});
    }

    // 日期选择
    $('.date').layDate();

    // 表格
    $('#grid-table').createGrid({
        url: ctx + '/showcase/sample/list',
        autoHeight: true,
        sortable: false,
        resizable: false,
        postData: {'search.deleted_eq': false},
        colModel:[
            {label: '编号', name: 'id', width: 60, fixed:true},
            {label: '姓名', name: 'name', width: 100},
            {label: '年龄', name: 'age', width: 50},
            {label: '出生日期', name: 'birthday', width: 100},
            {label: '性别', name: 'sex', width: 70, formatter: $.constant.getSex},
            {label: '是否显示', name: 'show', width: 80, formatter: $.constant.getBool}
        ],
        pager : '#grid-pager'
    });

    // 查询
    $('#search').on('click', function(){
        var form = $.object.trim($('#searchForm').serializeForm(), true);
        reloadTable(form);
    });
    // 新增
    $('#create').on('click', function(){
        $.app.openDialog('新增示例', ctx + '/showcase/sample/create', {
            btn: false,
            area: ['400px', '350px'],
            success: initValidationEngine
        });
    });
    // 修改
    $('#update').on('click', function(){
        var id = getSelectRowId();
        if (id) {
            $.app.openDialog('编辑示例', ctx + '/showcase/sample/'+id + '/update', {
                btn: false,
                area: ['400px', '350px'],
                success: initValidationEngine
            });
        }
    });
    // 删除
    $('#delete').on('click', function(){
        var id = getSelectRowId();
        if (id) {
            $.app.confirm('确认删除？', function(index){
                $.post(ctx + '/showcase/sample/'+id+'/delete.json', function(ret){
                    console.log(ret)
                    if (ret.success) {
                        $.app.alert('删除成功', function(){
                            reloadTable();
                            $.app.close(index);
                        });
                    } else {
                        $.app.alert(ret.message, reloadTable);
                    }
                }, 'json', true)
            })
        }
    });
    // 刷新
    $('#refresh').on('click', function(){
        reloadTable();
    });

    // 保存
    $(document).on('submit', '#editForm', function(e){
        e.preventDefault();

        var form = $(this).serialize();
        $.ajax({
            url: ctx+'/showcase/sample/ajaxCreate',
            type: 'POST',
            data: form,
            loading: true,
            headers: {Accept: 'application/json; charset=utf-8'},
            success: function(ret) {
                if (ret.success) {
                    $.app.alert(ret.message, function(){
                        reloadTable();
                        $.app.close();
                    });
                } else {
                    $.app.alert(ret.error[0]);
                }
            }
        })
    })
});